
#include "common.c"
#include "thread_pool.c"

#define MAX_LINE 1024
#define  BLOCK_QUEUE_SIZE   100
#define  THREAD_NUMBER      4

char process_char(char c) {
	if (c >= 'a' && c <= 'z') {
		return c - 32;
	} else if (c >= 'A' && c <= 'Z') {
		return c + 32;
	}
	return c;
}

void thread_process(int fd) {
	char outbuf[MAX_LINE + 1];
	size_t outbuf_used = 0;
    ssize_t result;

	for (;;) {
		char ch;
		result = read(fd, &ch, 1);
		if (result == 0) {
			close(fd);
			break;
		} else if (result == -1) {
			perror("read error");
			break;
		}

		if (outbuf_used < sizeof(outbuf)) {
            outbuf[outbuf_used++] = process_char(ch);
        }

        if (ch == '\n') {
            write(fd, outbuf, outbuf_used);
            outbuf_used = 0;
            continue;
        }
	}
}


void *thread_run(void *arg) {
    pthread_t tid = pthread_self();
    pthread_detach(tid);

    block_queue *blockQueue = (block_queue *) arg;
    while (1) {
        int fd = block_queue_pop(blockQueue);
        printf("get fd in thread, fd==%d, tid == %d\n", fd, tid);
        thread_process(fd);
    }
}

int main() {
	struct sockaddr_in client_sockaddr;
	int sin_size;
	int listener_fd = tcp_server_listen(SERVPORT);
	block_queue blockQueue;
	block_queue_init(&blockQueue, BLOCK_QUEUE_SIZE);

	thread_array = calloc(THREAD_NUMBER, sizeof(Thread));
    int i;
    for (i = 0; i < THREAD_NUMBER; i++) {
        pthread_create(&(thread_array[i].thread_tid), NULL, thread_run, (void *) &blockQueue);
    }

	for (;;) {
		int fd = accept(listener_fd, (struct sockaddr *) &client_sockaddr, &sin_size);
		if (fd < 0) {
			perror("accept failed");
			exit(1);
		}
		
		block_queue_push(&blockQueue, fd);
	}

	return 0;
}
